package blow.sky.quoted.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description BearToken工具类
 * @Author 孙焰明
 * @Date 2021/5/20 16:55
 */

@Component
public class BearTokenUtil
{
	@Value("${jwt.secret}")
	private String secret;
	@Value("${jwt.issuer}")
	private String issuer;
	@Value("${jwt.time}")
	private int expireTime;

	/**
	 * 根据登录用户的邮箱创建Token
	 * @param email 用户邮箱
	 * @return token，失败则返回null
	 */
	public String createToken(String email)
	{
		Algorithm algorithm = Algorithm.HMAC256(secret);
		String token = null;
		Map<String, String> payload = new HashMap<>();
		payload.put("email", email);
		try {
			token = JWT.create()
					.withIssuer(issuer)
					.withExpiresAt(new Date(System.currentTimeMillis() + expireTime * 1000 * 3600))
					.withPayload(payload)
					.sign(algorithm);
		}
		catch (JWTCreationException e) {
			e.printStackTrace();
		}
		return token;
	}

	/**
	 * 验证Token
	 * @param token 登录的token
	 * @return token中的email，失败则返回null
	 */
	public String verifyToken(String token)
	{
		if (token != null)
		{
			Algorithm algorithm = Algorithm.HMAC256(secret);
			try {
				JWTVerifier verifier = JWT.require(algorithm)
						.withIssuer(issuer)
						.build();
				DecodedJWT jwt = verifier.verify(token);
				String email = jwt.getClaim("email").asString();
				return email;
			} catch (JWTVerificationException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
}
